package com.swz.dcrm.adpter;

import android.content.Context;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.swz.dcrm.R;
import com.swz.dcrm.base.ViewHolder;
import com.swz.dcrm.model.MultipleChoice;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class MultipleChoiceAdapter<T> extends CustomAdapter<MultipleChoice<T>> {


    private boolean isSingle;
    private Map<Integer,T> map=new HashMap<>();
    private int index=-1;

    public MultipleChoiceAdapter(Context context, List<MultipleChoice<T>> datas,boolean isSingle) {
        super(context, R.layout.item_multiple_choice, datas);
        this.isSingle=isSingle;
    }



    @Override
    protected void convert(ViewHolder holder, MultipleChoice<T> tMultipleChoice, int position) {
        holder.setText(R.id.tv_tag,tMultipleChoice.getTag());
        CheckBox checkBox=holder.getView(R.id.cb);
        if(!isSingle){
            holder.itemView.setOnClickListener(v -> {
                checkBox.setChecked(!checkBox.isChecked());
            });
            checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if(isChecked){
                    map.put(position,tMultipleChoice.getT());
                }else {
                    map.remove(position);
                }
            });
            if(addHasCheckedList()!=null&&addHasCheckedList().size()>0){
                for(String s:addHasCheckedList()){
                    if(s.equals(tMultipleChoice.getTag())){
                        checkBox.setChecked(true);
                        break;
                    }
                }
            }
        }else {
            checkBox.setClickable(false);
            if(index==position){
                checkBox.setChecked(true);
            }else {
                checkBox.setChecked(false);
            }
            holder.itemView.setOnClickListener(v -> {
                index=position;
                map.clear();
                map.put(position,tMultipleChoice.getT());
                notifyDataSetChanged();
            });
        }


    }

    public abstract List<String> addHasCheckedList();

    public List<T> getCheckedList(){
        List<T> list=new ArrayList<>(map.values());
        return list;
    }
}
